﻿using Common.Mvvm.Navigation.Regions.Behaviors;
using Common.Mvvm.Navigation.Regions;
using Syncfusion.Windows.Tools.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;

namespace Syncfusion.Lib.Extensions
{

    public class SfDocumentRegionActiveAwareBehavior : RegionBehavior, IHostAwareRegionBehavior
    {
        public const string BehaviorKey = "DocumentRegionActiveAwareBehavior";
        DependencyObject? _hostControl;
        public DependencyObject? HostControl
        {
            get => _hostControl;
            set => _hostControl = value as DockingManager;
        }

        protected override void OnAttach()
        {
            if ((HostControl as DockingManager)?.DocContainer is DocumentContainer documentContainer)
            {
                documentContainer.AddTabDocumentAtLast = true;
                documentContainer.ActiveDocumentChanged += DocumentRegionActiveAwareBehavior_ActiveDocumentChanged;
            }
        }

        private void DocumentRegionActiveAwareBehavior_ActiveDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (e.OldValue != null)
            {
                var item = e.OldValue;

                //are we dealing with a ContentPane directly
                if (Region != null && Region.Views.Contains(item) && Region.ActiveViews.Contains(item))
                {
                    Region.Deactivate(item);
                }
                else
                {
                    //now check to see if we have any views that were injected
                    if (item is ContentControl contentControl)
                    {
                        var injectedView = contentControl.Content;
                        if (Region != null && Region.Views.Contains(injectedView) && Region.ActiveViews.Contains(injectedView))
                            Region.Deactivate(injectedView);
                    }
                }
            }

            if (e.NewValue != null)
            {
                var item = e.NewValue;

                //are we dealing with a ContentPane directly
                if (Region != null && Region.Views.Contains(item) && !this.Region.ActiveViews.Contains(item))
                {
                    Region.Activate(item);
                }
                else
                {
                    //now check to see if we have any views that were injected
                    if (item is ContentControl contentControl)
                    {
                        var injectedView = contentControl.Content;
                        if (Region != null && Region.Views.Contains(injectedView) && !this.Region.ActiveViews.Contains(injectedView))
                            Region.Activate(injectedView);
                    }
                }
            }
        }
    }
}
